package cn.botter.wechat.handler;

import cn.botter.wechat.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: bo-club
 * @BelongsPackage: cn.botter.wechat.handler
 * @Author: 爱写Bug的Botter
 * @CreateTime: 2025-03-21:22:27
 * @Description: 描述
 * @Version: 1.0
 */
@Component
@Slf4j
public class ReceiveTextMsgHandler implements WeChatMsgHandler{
    @Resource
    private RedisUtil redisUtil;
    private static final String LOGIN_PREFIX = "loginCode";
    @Override
    public WeChatMsgTypeEnum getMsgType() {
        return WeChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> msgType) {
        log.info("接受到用户发送文本消息事件");
        String content = msgType.get("Content") == null ? "" : msgType.get("Content");
        if (!"验证码".equals(content)){
            return "";
        }
        String fromUserName = msgType.get("FromUserName");
        String toUserName = msgType.get("ToUserName");

        Long rebackNum = (long) new Random().nextInt(900000)+100000;
        String numKey = redisUtil.buildKey(LOGIN_PREFIX,rebackNum.toString());
        redisUtil.setNx(numKey,fromUserName, 5L , TimeUnit.MINUTES);

        String responseContent = "您当前的验证码为:["+rebackNum+"],五分钟内有效!";
        String replyContent = "" +
                "<xml><ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "<FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "<CreateTime>1742632552</CreateTime>\n" +
                "<MsgType><![CDATA[text]]></MsgType>\n" +
                "<Content><![CDATA["+responseContent+"]]></Content>\n" +
                "<MsgId>24948502409438544</MsgId>\n" +
                "</xml>";
        return replyContent;
    }
}
